package messagebus

import (
	"encoding/json"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
)

type EzUserMessage struct {
	Uid     int64  `json:"uid"`
	Title   string `json:"title"`
	Message string `json:"message"`
	Params  ss.M   `json:"params"`
}

func NewEzMessage(message string) *EzUserMessage {
	return &EzUserMessage{
		Message: message,
		Params:  ss.M{},
	}
}

// SetUid 设置用户ID
func (m *EzUserMessage) SetUid(uid int64) *EzUserMessage {
	m.Uid = uid
	return m
}

// SetParams 设置参数 (key, value)
func (m *EzUserMessage) SetParams(key string, value interface{}) *EzUserMessage {
	m.Params[key] = value
	return m
}

// SetTitle 设置标题
func (m *EzUserMessage) SetTitle(title string) *EzUserMessage {
	m.Title = title
	return m
}

// SetMessage 设置消息
func (m *EzUserMessage) SetMessage(message string) *EzUserMessage {
	m.Message = message
	return m
}

// Send 发送用户消息
func (m *EzUserMessage) Send() {
	ez.NsqProducer.Publish(ez.EzTopicMessage, ez.JsonEncode(m))
}

func HandleUserMessage(channel string, handler func(um *EzUserMessage)) {
	ez.CreateNsqHandler(ez.EzTopicMessage, channel, func(content []byte) error {
		userMessage := new(EzUserMessage)
		_ = json.Unmarshal(content, userMessage)
		handler(userMessage)
		return nil
	})
}
